<template>
  <BasicModal title="产品选择" v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <div class="flex-col" style="width: 100%">
          当前选择的产品：
          <div class="selected">{{ selectedTips }}</div>
        </div>
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script setup lang="ts">
  import { computed } from 'vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { OrderStatusEnum } from '@/enums/orderEnum';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicTable, useTable } from '@/components/Table';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { productColumns, productFormSchema } from '@/views/production/logistics/data';

  const { OrderModule } = mcApi;
  const { SalesOrderApi } = OrderModule;

  const [registerTable, { reload, getSelectRows, setSelectedRowKeys }] = useTable({
    striped: false,
    bordered: true,
    immediate: false,
    canResize: false,
    rowKey: 'orderId',
    useSearchForm: true,
    showIndexColumn: false,
    api: SalesOrderApi.getSalesOrderPage,
    columns: productColumns,
    rowSelection: {
      type: 'checkbox',
    },
    formConfig: {
      labelWidth: 100,
      schemas: productFormSchema,
    },
    beforeFetch: (arg) => {
      arg.desc = 'cso.created_time';
      arg.status = OrderStatusEnum.WAITING_TO_SHIP;
    },
    afterFetch: (arg) => {
      arg.forEach((item: any) => {
        const orderItem = item?.orderItemList?.[0];
        Object.keys(orderItem).forEach((key) => {
          item[key] = orderItem[key];
        });
      });
    },
  });
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    setModalProps({
      width: 1000,
      minHeight: 50,
      confirmLoading: false,
    });
    const { dataSource } = data;
    setSelectedRowKeys(dataSource?.map?.((data: any) => data.orderId) || []);
    await reload();
  });

  const selectedTips = computed(() => {
    let text = '';
    const rows = getSelectRows();
    rows.forEach((row) => {
      const { spuName, orderCode } = row;
      text += `${text ? '，' : ''}${spuName}（${orderCode}）`;
    });
    return text;
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['ok']);
  function handleOk() {
    const rows = getSelectRows();
    if (!rows) {
      createMessage.error('请选择产品！');
      return;
    }
    emits('ok', rows);
  }
</script>

<style scoped lang="less">
  .selected {
    width: 100%;
    margin-top: 5px;
    min-height: 44px;
    padding: 10px 20px;
    border-radius: 5px;
    text-align: center;
    border: 1px solid #e8e8e8;
  }
</style>
